import React, { Component } from 'react'
import { observer } from 'mobx-react'
import { get } from 'lodash'

import { Loading, Columns, Column } from '@kube-design/components'
import { Card } from 'components/Base'

import { getLastMonitoringData } from 'utils/monitoring'

import ClusterMonitorStore from 'stores/monitoring/cluster'

import PieCard from './PieCard'
import PieChart from './PieChart'
import styles from './index.scss'

const MetricTypes = {
  cpu_usage: 'cluster_cpu_usage',
  cpu_total: 'cluster_cpu_total',
  memory_usage: 'cluster_memory_usage_wo_cache',
  memory_total: 'cluster_memory_total',
  disk_size_usage: 'cluster_disk_size_usage',
  disk_size_capacity: 'cluster_disk_size_capacity',
  pod_count: 'cluster_pod_running_count',
  pod_capacity: 'cluster_pod_quota',
}

@observer
export default class ResourcesUsage extends Component {
  monitorStore = new ClusterMonitorStore({ cluster: this.props.cluster })

  constructor(props) {
    super(props)
    this.state = {
      totalData: {},
      cpuValue: '',
      memoryValue: '',
      resourceData: [],
    }
  }

  componentDidMount() {
    this.queryCupMemoryTotalData()
    this.queryCupMemoryValueData()
    this.queryResourceData()
    this.fetchData()
  }

  queryCupMemoryTotalData = () => {
    request
      .get(
        '/kapis/clusters/host/tenant.kubesphere.io/v1alpha2/workspaces/demo-workspace/resourcequotas/demo-workspace',
        {}
      )
      .then(res => {
        const totalData = res.status.total
        this.setState(() => ({
          totalData: totalData.hard,
        }))
      })
  }

  queryCupMemoryValueData = () => {
    request
      .get(
        '/kapis/clusters/host/monitoring.kubesphere.io/v1alpha3/workspaces/demo-workspace?workspace=demo-workspace&start=1672709826&end=1672796226&step=3600s&times=24&metrics_filter=workspace_cpu_usage%7Cworkspace_memory_usage_wo_cache%7Cworkspace_disk_size_usage%24',
        {}
      )
      .then(res => {
        const responseData = res.results
        const cpu_usage = responseData.filter(item => {
          return item.metric_name === 'workspace_cpu_usage'
        })

        const memory_usage = responseData.filter(item => {
          return item.metric_name === 'workspace_memory_usage_wo_cache'
        })
        const cpuValue = cpu_usage?.[0]?.data?.result?.[0]?.values || 0

        const memoryValue = memory_usage?.[0]?.data?.result?.[0]?.values || 0
        this.setState(() => ({
          cpuValue: cpuValue?.[cpuValue.length - 1]?.[1] || [0],
          memoryValue: memoryValue?.[memoryValue.length - 1]?.[1] || 0,
        }))
      })
  }

  queryResourceData = () => {
    request
      .get(
        '/kapis/clusters/host/monitoring.kubesphere.io/v1alpha3/workspaces/demo-workspace?workspace=demo-workspace&start=1672718162&end=1672804562&step=3600s&times=24&metrics_filter=workspace_deployment_count%7Cworkspace_statefulset_count%7Cworkspace_daemonset_count%7Cworkspace_job_count%7Cworkspace_cronjob_count%7Cworkspace_pvc_count%7Cworkspace_service_count%7Cworkspace_ingresses_extensions_count%7Cworkspace_pod_running_count%24',
        {}
      )
      .then(res => {
        const responseData = res.results
        this.setState(() => ({
          resourceData: responseData || [],
        }))
        console.log('000', res)
      })
  }

  get metrics() {
    return this.monitorStore.data
  }

  getValue = data => get(data, 'value[1]', 0)

  fetchData = () => {
    this.monitorStore.fetchMetrics({
      metrics: Object.values(MetricTypes),
      last: true,
    })
  }

  getResourceOptions = () => {
    const data = getLastMonitoringData(this.metrics)
    return [
      {
        name: 'CPU',
        unitType: 'cpu',
        used: this.getValue(data[MetricTypes.cpu_usage]),
        total: this.getValue(data[MetricTypes.cpu_total]),
      },
      {
        name: t('MEMORY'),
        unitType: 'memory',
        used: this.getValue(data[MetricTypes.memory_usage]),
        total: this.getValue(data[MetricTypes.memory_total]),
      },
      {
        name: t('POD'),
        unitType: '',
        used: this.getValue(data[MetricTypes.pod_count]),
        total: this.getValue(data[MetricTypes.pod_capacity]),
      },
    ]
  }

  getRadarOptions = options =>
    options.map(option => ({
      name: option.name,
      usage: Math.round((option.used * 100) / (option.total || option.used)),
    }))

  render() {
    const options = this.getResourceOptions()
    const radarOptions = this.getRadarOptions(options)

    return (
      <Card className={styles.storageBox}>
        <Loading spinning={this.monitorStore.isLoading}>
          <Columns>
            <Column className="is-narrow is-4">
              <Card
                className={styles.storageCondition}
                title="内存/存储使用情况"
              >
                <PieCard
                  title={'内存 GB'}
                  used={15}
                  total={this.state.totalData['limits.memory']}
                />
                <PieCard
                  title={'CPU core'}
                  used={10}
                  total={this.state.totalData['limits.cpu']}
                />
              </Card>
            </Column>
            <Column className="is-narrow is-8">
              <Card className={styles.storageCondition} title="应用资源情况">
                <div className={styles.wrapper}>
                  <PieChart resourceData={this.state.resourceData} />
                </div>
              </Card>
            </Column>
          </Columns>
        </Loading>
      </Card>
    )
  }
}
